package myCaptcha

import (
	"bytes"
	"encoding/base64"
	"gdshop-admin-go-api/library/response"
	"github.com/afocus/captcha"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/grand"
	"image/color"
	"image/png"
)

// CreateCaptcha 生成验证码
func CreateCaptcha(w, h int) *response.JsonResponse {
	cap := captcha.New()

	// 设置字体文件
	if err := cap.SetFont("./res/comic.ttf"); err != nil {
		panic(err.Error())
	}
	cap.SetSize(w, h)                                             // 设置图片大小
	cap.SetDisturbance(captcha.MEDIUM)                            // 设置干扰
	cap.SetFrontColor(color.RGBA{R: 255, G: 255, B: 255, A: 255}) // 设置字体颜色
	cap.SetBkgColor(color.RGBA{})                                 // 设置背景颜色
	img, exactnessStr := cap.Create(4, captcha.NUM)               // 创建，第一个参数是验证码的数量，第二个是类型
	// 转换成为 base64
	emptyBuff := bytes.NewBuffer(nil) //开辟一个新的空buff
	err := png.Encode(emptyBuff, img) //img写入到buff
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	imgStr := base64.StdEncoding.EncodeToString(emptyBuff.Bytes()) //buff转成base64

	captchaId := grand.S(10)
	// 把验证码写入缓存，方便验证
	g.Redis().Do("SET", "captcha:"+captchaId, exactnessStr, "EX", "60")

	return response.SuccessByRequestMessageData(nil, "成功", g.Map{
		"captchaId": captchaId,
		"img":       "data:image/png;base64," + imgStr,
	})
}

// VerifyCaptcha 校验验证码
func VerifyCaptcha(captchaId, code string) bool {
	if captchaId == "" && code == "" {
		return false
	}
	v, _ := g.Redis().DoVar("GET", "captcha:"+captchaId)
	jieguo := v.String() == code

	// 不管验证是否成功，删除缓存中的验证码
	g.Redis().Do("DEL", "captcha:"+captchaId)

	return jieguo
}
